package com.yuntu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuntu.annotation.AuthCheck;
import com.yuntu.common.BaseResponse;
import com.yuntu.common.DeleteRequest;
import com.yuntu.common.ResultUtils;
import com.yuntu.demo.constant.UserConstant;
import com.yuntu.demo.dto.space.*;
import com.yuntu.demo.entity.Space;
import com.yuntu.demo.enums.SpaceLevelEnum;
import com.yuntu.demo.vo.LoginUserVO;
import com.yuntu.demo.vo.SpaceVO;
import com.yuntu.exception.ErrorCode;
import com.yuntu.exception.ThrowUtils;
import com.yuntu.exception.bizException;
import com.yuntu.manager.auth.SpaceUserAuthManager;
import com.yuntu.service.ISpaceService;
import com.yuntu.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 空间 前端控制器
 * </p>
 *
 * @author k
 * @since 2025-03-24
 */
@RestController
@RequestMapping("/space")
@Api("空间管理")
public class SpaceController {
    @Resource
    ISpaceService spaceService;
    @Resource
    IUserService userService;
    @Autowired
    private SpaceUserAuthManager spaceUserAuthManager;

    @PostMapping("add")
    @ApiOperation("添加空间")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest,
                         HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest==null,ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser==null,ErrorCode.NOT_LOGIN_ERROR);
        long spaceId = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(spaceId);
    }
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("修改空间")
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        //先判断是否有该空间
        if(spaceUpdateRequest.getId()==null){
            throw new bizException(ErrorCode.PARAMS_ERROR);
        }
        //查出数据
        Space oldspace = spaceService.getById(spaceUpdateRequest.getId());
        if(oldspace==null){
            throw new bizException(-1,"没有该空间");
        }
        Space space=new Space();
        BeanUtils.copyProperties(spaceUpdateRequest,space);
       //填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        //修改数据库
        boolean update = spaceService.updateById(space);
        ThrowUtils.throwIf(!update,ErrorCode.SYSTEM_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("delete")
    @ApiOperation("删除空间")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest,
                                               HttpServletRequest request) {
        //判断是否存在
        if(deleteRequest.getId()==null){
            throw new bizException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUser = userService.getLoginUser(request);
        spaceService.deleteSpace(deleteRequest.getId(), loginUser);
        return ResultUtils.success(true);
    }
    @GetMapping("/list/level")
    @ApiOperation("得到空间级别种类")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }
    @GetMapping("get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("管理员根据Id查空间")
    public BaseResponse<Space> getSpaceById(Long id,HttpServletRequest request) {
        ThrowUtils.throwIf(id == null,ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space==null,new bizException(-1,"没有该空间"));
        return ResultUtils.success(space);
    }

    @GetMapping("get/vo")
    @ApiOperation("查空间vo")
    public BaseResponse<SpaceVO> getSpaceVoById(Long id, HttpServletRequest request) throws InterruptedException {
        ThrowUtils.throwIf(id == null,ErrorCode.PARAMS_ERROR);
//        Thread.sleep(1000);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space==null,new bizException(-1,"没有该空间"));
        SpaceVO spaceVo = spaceService.getSpaceVo(space, request);
        //获取权限列表
        LoginUserVO loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVo.setPermissionList(permissionList);
        return ResultUtils.success(spaceVo);
    }
    @PostMapping("list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("管理员分页查询所有空间")
    public BaseResponse<Page<Space>> getSpacePage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                  HttpServletRequest request) {
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(spaceQueryRequest);
        Long current = (long) spaceQueryRequest.getCurrent();
        Long pageSize = (long) spaceQueryRequest.getPageSize();
        Page<Space> page = spaceService.page(new Page<Space>(current, pageSize), queryWrapper);
        return ResultUtils.success(page);
    }
    @PostMapping("list/page/vo")
    @ApiOperation("用户分页查询所有空间")
    public BaseResponse<Page<SpaceVO>> getSpacePageVo(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                      HttpServletRequest request) {
        LoginUserVO loginUser = userService.getLoginUser(request);
        spaceQueryRequest.setUserId(loginUser.getId());
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(spaceQueryRequest);
        Long current = (long) spaceQueryRequest.getCurrent();
        Long pageSize = (long) spaceQueryRequest.getPageSize();
        //防止爬虫
        ThrowUtils.throwIf(pageSize>30,ErrorCode.PARAMS_ERROR);
        Page<Space> page = spaceService.page(new Page<Space>(current, pageSize), queryWrapper);
        Page<SpaceVO> pictureVOPage = spaceService.getSpaceVOPage(page, request);
        return ResultUtils.success(pictureVOPage);
    }
    @PostMapping("edit")
    @ApiOperation("编辑空间")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest,
                                             HttpServletRequest request) {
        LoginUserVO loginUser = userService.getLoginUser(request);
        spaceService.editSpace(spaceEditRequest,loginUser);
        return ResultUtils.success(true);
    }
}
